package com.blue.base.common.jwt;

import com.blue.base.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Configuration
@ConditionalOnProperty(value = "jwt.token.enable")
public class JwtRsaKeyAutoConfig implements CommandLineRunner {

    public static RsaKeyConfig rsaKeyConfig = new RsaKeyConfig();

    @Override
    public void run(String... args) throws Exception {
        log.info("初始化jwt公私密钥....");
        boolean rsaKeyExisted = RedisUtils.hasKey(JwtConfig.REDIS_USER_PRI_KEY)
                && RedisUtils.hasKey(JwtConfig.REDIS_USER_PUB_KEY);
        if (rsaKeyExisted) {
            log.info("Redis已有密钥数据，直接设置该服务的配置对象的公钥、私钥信息");
            rsaKeyConfig.setPrivateKey(RsaKeyUtil.toBytes(RedisUtils.get(JwtConfig.REDIS_USER_PRI_KEY)));
            rsaKeyConfig.setPublicKey(RsaKeyUtil.toBytes(RedisUtils.get(JwtConfig.REDIS_USER_PUB_KEY)));
            return;
        }
        log.info("Redis无密钥数据，直接生成并存储到redis，设置该服务配置对象的公钥、私钥信息");
        Map<String, byte[]> keyMap = RsaKeyUtil.generateKey();
        rsaKeyConfig.setPrivateKey(keyMap.get("pri"));
        rsaKeyConfig.setPublicKey(keyMap.get("pub"));
        RedisUtils.set(JwtConfig.REDIS_USER_PRI_KEY, RsaKeyUtil.toHexString(keyMap.get("pri")), JwtConfig.JWT_SECRET_EXPIRE);
        RedisUtils.set(JwtConfig.REDIS_USER_PUB_KEY, RsaKeyUtil.toHexString(keyMap.get("pub")), JwtConfig.JWT_SECRET_EXPIRE);
    }
}
